
#include "commmsg.h"
#include "commerrno.h"
#include "../cmd/dataprepare.h"
#include "../rank/CRankMgr.h"
#include "cmdrank.h"


CT_REGISTER_ASYNCCMD(ID_MAIN_RANK, CCmdClanRank);
int CCmdClanRank::Do(void* pData)
{
    //解析消息
    CCmdPBDoParam* pstParam = (CCmdPBDoParam*) pData;
    pstMainCtrl = (CMainCtrl*) pstParam->m_pMain;

    if (pstParam->m_pstMsgHead->msgid() != ID_MAIN_RANK ||
        pstParam->m_pstMsgHead->msgtype() != CSMsgDef::EMT_REQUEST)
    {
        CT_ERROR(("Cmd Stat Err Cmd=%d CmdID=%d Tpye=%d",
            ID_MAIN_RANK,
            pstParam->m_pstMsgHead->msgid(),
            pstParam->m_pstMsgHead->msgtype()));
        return Done(RET_SYS_ERROR);
    }

    stMsgHead = *(pstParam->m_pstMsgHead);
    stEnpHead = *(pstParam->m_pstEnpHead);
    int iRet = pstMainCtrl->DecodePBMsg(stReq, pstParam);
    if (iRet)
    {
        return AnsClients(iRet);
    }
    //消息解析结束

    //检查登录
    _uiGID = stReq.gid();
    iRet = pstMainCtrl->CheckLogin(_uiGID, stEnpHead);
    if (iRet != RET_OK)
    {
        return AnsClients(iRet);
    }

    LogicDo(RET_OK);

    return RET_OK;
}

int CCmdClanRank::LogicDo (int iRet)
{
    if (iRet)
    {
        return AnsClients(iRet);
    }

    if (4 == stReq.opt())
    {
        PREPARE_PLAYER_DETAIL_INFO(this, stReq.gid());

        int iGidIndex = pstMainCtrl->m_stPlayerDetailInfoHash.HashFind(stReq.gid());
        if (iGidIndex < 0)
        {
            return AnsClients(RET_SYS_ERROR);
        }
        CUserClan & stUserClan = pstMainCtrl->m_stPlayerDetailInfoHash[iGidIndex]._stUserClan;

        int iMyClanRank = pstMainCtrl->m_stClanMgr.GetClanRank(stReq.gid());
        int iTotalPages = 0;
        iRet = pstMainCtrl->m_stClanMgr.GetClanInfo (stReq.page_beg(), stReq.page_end(), stReq.per_page_cnt(),
                                                     stUserClan, (*(stAns.mutable_clans())), iTotalPages);
        if (iRet)
        {
            return AnsClients(iRet);
        }

        stAns.set_total_page_num(iTotalPages);
        stAns.set_my_rank(iMyClanRank);
        stAns.set_next_refresh_time(pstMainCtrl->m_stClanMgr._iLastRankTime + MAX_CLAN_SORT_TIME);
    }
    else
    {
        iRet = pstMainCtrl->m_stRankMgr.GetRank(stReq, stAns);
    }
    
    return AnsClients(iRet);
}

int CCmdClanRank::AnsClients(int iRet)
{
    stMsgHead.set_msgret(iRet);
    stMsgHead.set_msgtype(CSMsgDef::EMT_ANSWER);

    if (iRet != RET_OK)
    {
        pstMainCtrl->ReturnMsgHead(stMsgHead, stEnpHead);
        return Done(iRet);
    }

    stAns.set_page_beg_no(stReq.page_beg());
    stAns.set_opt(stReq.opt());
    pstMainCtrl->m_stEncodeBuf.Clear();
    pstMainCtrl->EncodePBMsg(stMsgHead, pstMainCtrl->m_stEncodeBuf);
    pstMainCtrl->EncodePBMsg(stAns, pstMainCtrl->m_stEncodeBuf);
    if (pstMainCtrl->AnswerToClient(stEnpHead, pstMainCtrl->m_stEncodeBuf,true))
    {
        CT_WARNING((""));
        return Done(RET_SYS_ERROR);
    }

    return Done(iRet);
}